package com.cryptape.cita_wallet.activity;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.R;
import com.cryptape.cita_wallet.adapter.MinerIncomeAdapter;
import com.cryptape.cita_wallet.bean.HttpResponse;
import com.cryptape.cita_wallet.bean.MiningOrderIncomeBean;
import com.cryptape.cita_wallet.bean.MiningOrderIncomeItem;
import com.cryptape.cita_wallet.bean.MiningWithdrawDetailBean;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.service.http.WalletService;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.view.ExtractDialog;
import com.cryptape.cita_wallet.view.TitleBar;
import com.cryptape.cita_wallet.view.button.CommonButton;
import com.cryptape.cita_wallet.view.dialog.SimpleSelectDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.subscribers.SafeSubscriber;
import rx.Subscriber;

/**
 * Created by dengming on 26/2/20.
 */
public class MinerIncomeActivity extends NBaseActivity {
    private RecyclerView recyclerView;
    private MinerIncomeAdapter minerAdapter;
    private TitleBar mTitle;
    private TextView tv_balance_mgp;
    private TextView tv_balance_usd;
    private CommonButton btn_extract;
    private TextView tv_income_select_type;
    private TextView tv_balance;
    private SmartRefreshLayout refreshLayout;

    private boolean refreshType;
    private int page = 1;
    private boolean isMoreData = true;
    private static final String moneyType = "1";

    @Override
    protected int getContentLayout() {
        return R.layout.activity_miner_income;
    }

    @Override
    protected void initView() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.miner_income_recycler);
        mTitle = findViewById(R.id.title_bar);
        tv_balance_mgp = findViewById(R.id.tv_balance_mgp);
        tv_balance_usd = findViewById(R.id.tv_balance_usd);
        btn_extract = findViewById(R.id.btn_extract);
        tv_income_select_type = findViewById(R.id.tv_income_select_type);
        tv_balance = findViewById(R.id.tv_balance);

        initAdapter();
    }

    @Override
    protected void initData() {
        initMinerData();
    }

    private int selectTypeIndex = 0;

    @Override
    protected void initAction() {
//        tv_balance.setText(getString(R.string.));
        btn_extract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                getConfirmLockView();
                getConfirmTransferView();
            }
        });
        String[] types = new String[]{getString(R.string.profile_hint_item11), getString(R.string.alphago_hint_earnings), getString(R.string.currency_hint_extract), getString(R.string.log_hint_procedurefee)};
        tv_income_select_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleSelectDialog dialog = new SimpleSelectDialog(MinerIncomeActivity.this, Arrays.asList(types), -1);
                dialog.setMSelected(selectTypeIndex);
                dialog.setOnOkListener((view -> {
                    selectTypeIndex = dialog.getMSelected();
                    tv_income_select_type.setText(types[selectTypeIndex]);
                    dialog.dismiss();

                    List<MiningOrderIncomeItem> newDatas = new ArrayList<>();
                    if (selectTypeIndex == 0) {
//                        newDatas.addAll(datas);
                        minerAdapter.setDatas(datas);
                        minerAdapter.notifyDataSetChanged();
                    } else {
                        for (MiningOrderIncomeItem item : datas) {
                            if (item.getType() == selectTypeIndex) {
                                newDatas.add(item);
                            }
                        }
                        minerAdapter.setDatas(newDatas);
                        minerAdapter.notifyDataSetChanged();
                    }

                }));
            }
        });

        // 开启自动加载功能（非必须）
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshType = true;
                        page = 1;
                        initMinerData();//setNoMoreData(false);
                    }
                }, 2000);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshType = false;
                        if (!isMoreData) {
                            // 将不会再次触发加载更多事件
                            refreshLayout.finishLoadMoreWithNoMoreData();
                            return;
                        }
                        initMinerData();
                    }
                }, 2000);
            }
        });
        //触发自动刷新
        refreshLayout.autoRefresh();
    }

    private List<MiningOrderIncomeItem> datas = new ArrayList<>();
    private MiningOrderIncomeBean mData;
    private MiningWithdrawDetailBean detailBean;

    private void initMinerData() {
        TokenService.getMiningOrderIncome(page + "").subscribe(new Subscriber<MiningOrderIncomeBean>() {
            @Override
            public void onCompleted() {
                if (refreshType) {
                    refreshLayout.finishRefresh();
                    refreshLayout.resetNoMoreData();
                } else {
                    refreshLayout.setEnableLoadMore(true);
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onError(Throwable e) {
                if (refreshType) {
                    refreshLayout.finishRefresh();
                    refreshLayout.resetNoMoreData();
                } else {
                    refreshLayout.setEnableLoadMore(true);
                    refreshLayout.finishLoadMore();
                }
                Toast.makeText(MinerIncomeActivity.this, getString(R.string.network_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(MiningOrderIncomeBean data) {
//                if (data == null || data.getCode() != 0) {
//                    btn_extract.setEnabled(false);
//                    btn_extract.setBackgroundResource(R.drawable.button_corner_gray_shape);
//                    return;
//                }
                if (refreshType) {
                    refreshLayout.finishRefresh();
                    refreshLayout.resetNoMoreData();
                } else {
                    refreshLayout.setEnableLoadMore(true);
                    refreshLayout.finishLoadMore();
                }
                if (data != null) {
                    isMoreData = false;
                    if (data.getCode() != 0) {
                        return;
                    }
                    mData = data;
                    if (data.getData() != null) {
                        isMoreData = true;
                        if (page == 1) {
                            datas.clear();
                            getWithdrawDetail();
                            tv_balance_usd.setText("≈$" + data.getData().getBalanceValue());
                            tv_balance_mgp.setText(data.getData().getBalance());
                        }
                        if (data.getData().getList() != null) {
                            datas.addAll(data.getData().getList());
                        }
                        minerAdapter.notifyDataSetChanged();
                        page++;
                    }
                } else {
                    isMoreData = false;
                }
            }
        });
    }

    private void getWithdrawDetail() {
        showProgressBar();
        TokenService.getWithdrawIndex().subscribe(new Subscriber<MiningWithdrawDetailBean>() {
            @Override
            public void onCompleted() {
                dismissProgressBar();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressBar();
            }

            @Override
            public void onNext(MiningWithdrawDetailBean data) {
                dismissProgressBar();
                if (data == null || data.getCode() != 0) {
                    btn_extract.setEnabled(false);
                    btn_extract.setBackgroundResource(R.drawable.button_corner_gray_shape);
                    return;
                }
                detailBean = data;
            }
        });
    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        minerAdapter = new MinerIncomeAdapter(datas);
        recyclerView.setAdapter(minerAdapter);
    }

    private ProgressBar progressBar;
    ExtractDialog extractDialog;

    private void getConfirmTransferView() {
        if (detailBean == null) {
            return;
        }
        BigDecimal withdrawMoney = new BigDecimal(detailBean.getData().getMoney());
        if (withdrawMoney.compareTo(BigDecimal.TEN) < 0) {
            Toast.makeText(mActivity, getString(R.string.tip_minimum_withdrawal), Toast.LENGTH_SHORT).show();
            return;
        }
        if (isFastDoubleClick()) return;
        extractDialog = new ExtractDialog(this, (password, progressBar) -> {
            this.progressBar = progressBar;
            extractDialog.setButtonClickAble(false);
            progressBar.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(password)) {
                extractDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
            } else if (!WalletService.checkPassword(mActivity, password, DBWalletUtil.getCurrentWallet(this))) {
                extractDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
            } else {
                extractIncome();
            }
        });
        extractDialog.setConfirmData(DBWalletUtil.getCurrentWallet(this).address,
                detailBean.getData().getMoney() + "MGP",
                detailBean.getData().getServiceCharge());
    }

    private void extractIncome() {
        if (mData == null) {
            return;
        }
        TokenService.withdrawMiningIncome(mData.getData().getBalance()).subscribe(new Subscriber<HttpResponse>() {
            @Override
            public void onCompleted() {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                if (extractDialog != null) {
                    extractDialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(MinerIncomeActivity.this, getString(R.string.network_error), Toast.LENGTH_SHORT).show();
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                if (extractDialog != null) {
                    extractDialog.dismiss();
                }
            }

            @Override
            public void onNext(HttpResponse httpResponse) {
                if (httpResponse != null && httpResponse.getCode() == 0) {
                    Toast.makeText(MinerIncomeActivity.this, getString(R.string.withdrawal_success), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MinerIncomeActivity.this, getString(R.string.withdrawal_fail), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
